package com.example.demo.Data.User;

import com.example.demo.SecurityConfig.UserGrantedAuthority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.*;

public class UserBo extends User implements UserDetails
{
    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    private String password;
    private UserDo userDo;
    private static final Set<Long> loginUserIdSet = new HashSet<>();
    public UserBo(UserDo userDo)
    {
        super();
        this.userDo = userDo;
        this.password = userDo.getPassword();
        setAuth(userDo.getAuth());
        setDept_id(userDo.getDept_id());
        setDept_name(userDo.getDept_name());
        setId(userDo.getId());
        setName(userDo.getName());
        setType(userDo.getType());
    }

    public void setPassword(String password)
    {
        if (password.matches("^([0-9]|[a-z]|[A-Z]){6,}$"))
        {
            this.password = password;
        }
    }


    public static void loginUser(long userId)
    {
        loginUserIdSet.add(userId);
    }

    public static boolean isLoggedin(long userId)
    {
        return loginUserIdSet.contains(userId);
    }

    public static void logoutUser(long userId)
    {
        loginUserIdSet.remove(userId);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities()
    {
        List<UserGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new UserGrantedAuthority(getAuth()));
        authorities.add(new UserGrantedAuthority(getType()));
        return authorities;
    }

    @Override
    public String getPassword()
    {
        return passwordEncoder.encode(password);
    }

    @Override
    public String getUsername()
    {
        return this.getName();
    }

    @Override
    public boolean isAccountNonExpired()
    {
        return true;
    }

    @Override
    public boolean isAccountNonLocked()
    {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired()
    {
        return true;
    }

    @Override
    public boolean isEnabled()
    {
        return true;
    }

}
